package com.itic.appbase.framework.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;


public class IpAddressHelper {
	
	public static String INTRANET_IP = getIntranetIp(); // 内网IP
    public static String INTERNET_IP = getInternetIp(); // 外网IP
    
    /**
     * 获得内网IP
     * @return 内网IP
     */
    private static String getIntranetIp(){
        try{
            return InetAddress.getLocalHost().getHostAddress();
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }
	/**
     * 获取用户id测试方法
     * @param request
     * @return
     */
    public static String getRemortIP(HttpServletRequest request) {

        if (request.getHeader("x-forwarded-for") == null) {

            return request.getRemoteAddr();    

        }     

        return request.getHeader("x-forwarded-for");     

    }
    
    /**
     * 获取服务器的ip地址
     * @param request
     * @return
     */
    public static String getLocalhostIp(HttpServletRequest request){
    	String result="";
		try {
			InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
		    result = address.getHostAddress();//192.168.0.121
		} catch (Exception e) {
			e.printStackTrace();
		}
        return result;
    }
    

    /**
     * 获取服务器的端口
     * @param request
     * @return
     */
    public static String getLocalhostPort(HttpServletRequest request){
    	String result="";
		try {
			result = request.getServerPort()+"";
		} catch (Exception e) {
			e.printStackTrace();
		}
        return result;
    }
    
    /**
     * 获得外网IP
     * @return 外网IP
     */
    private static String getInternetIp(){
        try{
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            Enumeration<InetAddress> addrs;
            while (networks.hasMoreElements())
            {
                addrs = networks.nextElement().getInetAddresses();
                while (addrs.hasMoreElements())
                {
                    ip = addrs.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && ip.isSiteLocalAddress()
                            && !ip.getHostAddress().equals(INTRANET_IP))
                    {
                        return ip.getHostAddress();
                    }
                }
            }

            // 如果没有外网IP，就返回内网IP
            return INTRANET_IP;
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 获取服务器的IP端口项目名称
     * @param request
     * @return
     */
    public static String getLocalhostName(HttpServletRequest request){
    	String result="";
		try {
			StringBuffer clintMsg = new StringBuffer();
			clintMsg.append("http://");
			String ip = PropertyGetter.getString("app.remote.ip");
			clintMsg.append(ip);
	   	    clintMsg.append(":");
	   	    clintMsg.append(IpAddressHelper.getLocalhostPort(request));
	   	    clintMsg.append(request.getContextPath());
	   	    result = clintMsg.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
        return result;
    }
    
    /**
     * 获取WS服务器的IP端口项目名称
     * @param request
     * @return
     */
    public static String getLocalhostWs(HttpServletRequest request){
    	String result="";
		try {
			StringBuffer clintMsg = new StringBuffer();
			clintMsg.append("ws://");
			String ip = PropertyGetter.getString("app.remote.ip");
			clintMsg.append(ip);
			//clintMsg.append(IpAddressHelper.getInternetIp());
	   	    clintMsg.append(":");
	   	    clintMsg.append(IpAddressHelper.getLocalhostPort(request));
	   	    clintMsg.append(request.getContextPath());
	   	    result = clintMsg.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
        return result;
    }
    
    public static String getRemortIP4(){
    	String ip = null;
    	Enumeration allNetInterfaces;
    	try {
	    	allNetInterfaces = NetworkInterface.getNetworkInterfaces();
	    	while (allNetInterfaces.hasMoreElements()) {
		    	NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
		    	List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
		    	for (InterfaceAddress add : InterfaceAddress) {
		    	InetAddress Ip = add.getAddress();
		    	if (Ip != null && Ip instanceof Inet4Address) {
		    	ip = Ip.getHostAddress();
	    	}
    	}
    	}
    	} catch (SocketException e) {
    	// TODO Auto-generated catch block
    	// logger.warn("获取本机Ip失败:异常信息:"+e.getMessage());
    	}
    	return ip;
    }
    
}
